package com.base.self.service.impl;

import com.base.exception.CustomException;
import com.base.mapper.voipmapper.SbdDetailMapper;
import com.base.mapper.voipmapper.SubscribersMapper;
import com.base.mapper.voipmapper.UsersReleaseConfigMapper;
import com.base.po.voip.SbdDetail;
import com.base.po.voip.Subscribers;
import com.base.po.voip.UsersReleaseConfig;
import com.base.self.common.CommMember;
import com.base.self.service.CommissionService;
import com.base.utils.Produce;
import com.base.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分销相关实现类
 *
 * @author Administrator
 */
@Slf4j
@Service("CommissionService")
public class CommissionServiceImpl implements CommissionService {
    private final SubscribersMapper subscribersMapper;
    private final UsersReleaseConfigMapper usersReleaseConfigMapper;
    private final SbdDetailMapper sbdDetailMapper;

    public CommissionServiceImpl(SubscribersMapper subscribersMapper, UsersReleaseConfigMapper usersReleaseConfigMapper, SbdDetailMapper sbdDetailMapper) {
        this.subscribersMapper = subscribersMapper;
        this.usersReleaseConfigMapper = usersReleaseConfigMapper;
        this.sbdDetailMapper = sbdDetailMapper;
    }

    @Override
    public void agentCommission(String orderNo, String userId, BigDecimal paymentAmount) {
        log.warn("[agentCommission] orderNo={} buyUserId={} paymentAmount={}", orderNo, userId, paymentAmount);
        Subscribers subscribers = subscribersMapper.selectByPrimaryKey(userId);
        UsersReleaseConfig releaseConfig = usersReleaseConfigMapper.selectByParentId(subscribers.getParentid());
        if (releaseConfig == null) {
            log.warn("[agentCommission] 代理商未配置分销比列");
            return;
        }

        BigDecimal perCommission = new BigDecimal(0);// 当前奖励比例

        // 下单用户信息
        Subscribers buyUsers = new Subscribers();
        buyUsers.setMember(0);
        // 上级信息
        String parUsersId = subscribersMapper.findParList(userId);
        String[] parUsersIds = parUsersId.split(",");
        int memberLevel = 0;// 当前用户等级
        int perMemberLever = 0; // 上级用户等级
        for (int i = 1; i < parUsersIds.length; i++) {
            // 查询当前用户信息
            Subscribers parUsers = subscribersMapper.selectByPrimaryKey(parUsersIds[i]);

            if (parUsers == null) {
                log.warn("[agentCommission] 未查询到上级用户:UserId=" + userId + "&OrderId=" + orderNo);
                continue;
            }

            memberLevel = buyUsers.getMember();
            perMemberLever = parUsers.getMember();
            int compare = new BigDecimal(perMemberLever).compareTo(new BigDecimal(memberLevel));
            if (compare == -1 || compare == 0) {
                continue;
            } else {
                perCommission = releaseCommission(memberLevel, perMemberLever, releaseConfig);
                switch (perMemberLever) {
                    case 1:
                        gainCommission(parUsers.getId(), paymentAmount.multiply(perCommission), "二级代理收益", orderNo, releaseConfig);
                        break;
                    case 2:
                        gainCommission(parUsers.getId(), paymentAmount.multiply(perCommission), "一级代理收益", orderNo, releaseConfig);
                        break;
                }
            }

            buyUsers = parUsers;
        }
    }

    @Override
    public Map<String, BigDecimal> getCommission(String userId) {
        Map<String,BigDecimal> result = new HashMap<String,BigDecimal>();
        // 获取用户分销比例
        Map<String,Integer> level = subscribersMapper.getLevel(userId);
        if (null == level){
            result.put("toBeSetted",new BigDecimal(0));
            result.put("hasSetted",new BigDecimal(0));
            result.put("total",new BigDecimal(0));
            return result;
          //  throw new CustomException("未找到该代理的信息");
        }

        Subscribers subscribers = subscribersMapper.selectByPrimaryKey(userId);
        UsersReleaseConfig releaseConfig = usersReleaseConfigMapper.selectByParentId(subscribers.getParentid());
        if (null == releaseConfig) {
            log.warn("[agentCommission] 代理商未配置分销比列");
        }
        //收益
        BigDecimal rebit = releaseCommission(level.get("memberLevel"),level.get("perMemberLever"),releaseConfig);
        //待结算收益
        BigDecimal toBeSetted =  subscribersMapper.getTobeSetted(userId,rebit);
        //已结算收益
        BigDecimal hasSetted =  subscribersMapper.getHasSetted(userId);
        if(StringUtils.isNull(toBeSetted)){
            toBeSetted = new BigDecimal(0);
        }
        if(StringUtils.isNull(hasSetted)){
            hasSetted = new BigDecimal(0);
        }
        result.put("toBeSetted",toBeSetted);
        result.put("hasSetted",hasSetted);
        result.put("total",hasSetted.add(toBeSetted));
        return result;
    }

    @Override
    public List<Map<String, Object>> getCommisionDetail(String userId,BigDecimal rebit) {
        return subscribersMapper.getCommisionDetail(userId,rebit);
    }

    /**
     * 分销比例
     */
    public static BigDecimal releaseCommission(Integer memberLevel, Integer perMemberLever, UsersReleaseConfig releaseConfig) {
        // 实际分销比例
        Double releaseCommission = 0.00;
        // 分销比例
        Double commission = 0.00;
        // 上级分销比例
        Double shareCommission = 0.00;

        switch (memberLevel) {
            case 1:
                commission = releaseConfig.getAgentTwoRatio();
                break;
            case 2:
                commission = releaseConfig.getAgentOneRatio();
                break;
        }

        if(null == perMemberLever){
            return new BigDecimal(0);
        }

        switch (perMemberLever) {
            case 1:
                shareCommission = releaseConfig.getAgentTwoRatio();
                break;
            case 2:
                shareCommission = releaseConfig.getAgentOneRatio();
                break;
        }

        releaseCommission = shareCommission - commission;

        return new BigDecimal(releaseCommission).setScale(4, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 获取分销收益占比
     */
    public BigDecimal getRebit(String userId){
        Map<String,BigDecimal> result = new HashMap<String,BigDecimal>();
        // 获取用户分销比例
        Map<String,Integer> level = subscribersMapper.getLevel(userId);
        if (StringUtils.isNull(level)){
           return new BigDecimal(0);
        }

        Subscribers subscribers = subscribersMapper.selectByPrimaryKey(userId);
        UsersReleaseConfig releaseConfig = usersReleaseConfigMapper.selectByParentId(subscribers.getParentid());
        if (releaseConfig == null) {
            log.warn("[agentCommission] 代理商未配置分销比列");
        }
        //收益
        return releaseCommission(level.get("memberLevel"),level.get("perMemberLever"),releaseConfig);
    }
    // 分销记录
    public void gainCommission(String gainUserId, BigDecimal gainMoney, String gainContent, String gainOrderNo, UsersReleaseConfig releaseConfig) {
        if (gainMoney.compareTo(new BigDecimal(0)) == 0) {
            log.warn("[agentCommission] " + gainContent + "收益为零:UserId=" + gainUserId + "&OrderId=" + gainOrderNo);
            return;
        }

        try {
            SbdDetail sbdDetail = new SbdDetail();
            sbdDetail.setSbdUser(gainUserId);
            sbdDetail.setSbdTradeMoney(gainMoney);
            sbdDetail.setSbdTradeContext(gainContent);
            sbdDetail.setSbdStatus(1);
            sbdDetail.setSbdTradeTo(gainOrderNo);
            sbdDetail.setSbdStatement(1);
            sbdDetail.setSbdTime(Produce.getNowDate());
            sbdDetailMapper.insertSelective(sbdDetail);
            log.warn("[agentCommission] " + gainContent + "收益:UserId=" + gainUserId + "&OrderId=" + gainOrderNo);
        } catch (Exception e) {
            log.warn("[agentCommission] " + gainContent + "收益报错" + e);
        }
    }
}
